#include "trianglewindow.h"  

#include <QOpenGLContext>  

Renderer::Renderer(const QSurfaceFormat &format, Renderer *share, QScreen *screen)
	: m_initialized(false)
	, m_format(format)
{
	m_context = new QOpenGLContext(this);
	if (screen)
		m_context->setScreen(screen);
	m_context->setFormat(format);
	if (share)
		m_context->setShareContext(share->m_context);
	m_context->create();
}

TriangleWindow::TriangleWindow(const QSharedPointer<Renderer> &renderer)
	: m_renderer(renderer)
{
	setSurfaceType(QWindow::OpenGLSurface);
	setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);

	setGeometry(QRect(10, 10, 640, 480));

	setFormat(renderer->format());

	create();

	connect(this, SIGNAL(needRender(QSurface *, const QColor &, const QSize &)),
		renderer.data(), SLOT(render(QSurface *, const QColor &, const QSize &)));

}

void TriangleWindow::exposeEvent(QExposeEvent *)
{
	render();
}

void TriangleWindow::render()
{
	if (isExposed())
		emit needRender(this, QColor(51, 51, 101), size());
}

void Renderer::render(QSurface *surface, const QColor &color, const QSize &viewSize)
{
	if (!m_context->makeCurrent(surface))
		return;

	if (!m_initialized) {
		initialize();
		m_initialized = true;
	}

	glViewport(0, 0, viewSize.width(), viewSize.height());

	glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glColor3f(1.0, 0.0, 0.0);
	//glRectf(-0.5f, -0.4f, 0.5f, 0.5f);
	glPointSize(5.0f);
	glBegin(GL_POINTS);
		glVertex2i(100, 100);
		glVertex2i(50, 50);
		glVertex2i(70, 70);

		glVertex2f(0.3f, 0.3f);
		glVertex2f(-0.3f, -0.3f);
		glVertex2f(0.5f, 0.5f);

		glVertex2d(0.2, 0.5);
		glVertex2d(-0.4, -0.6);
		glVertex2d(0.3, 0.6);
	glEnd();

	glColor3f(1.0, 0.0, 0.0);
	glBegin(GL_LINES);
		glVertex2f(0.3f, 0.3f);
		glVertex2f(-0.3f, -0.3f);
		glVertex2f(0.5f, 0.5f);

		glVertex2d(0.2, 0.5);
		glVertex2d(-0.4, -0.6);
		glVertex2d(0.3, 0.6);
	glEnd();

	glFlush();

	m_context->swapBuffers(surface);

}

void Renderer::initialize()
{
	glClearColor(0.2f, 0.2f, 0.396078431f, 1.0f);
}